<?php

namespace app\admin\controller;

use app\admin\model\AreaPrice;
use app\admin\model\SpecialCateModel;
use app\common\controller\Adminbase;
use think\cache\driver\Redis;
use think\Db;
use think\Exception;

/**
 * 专项服务
 */
class Special extends Adminbase
{

    /**
     * SpecialModel模型对象
     * @var \app\admin\model\SpecialModel
     */
    protected $modelClass = null;

    protected function initialize()
    {
        parent::initialize();
        $this->modelClass = new \app\admin\model\SpecialModel;

    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Curd.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            [$page, $limit, $where, $sort, $order] = $this->buildTableParames();

            $list = $this->modelClass
                ->withJoin(['cate'])
                ->where($where)
                ->order('sort desc,id desc')

                ->paginate($limit);

            foreach ($list as $row) {
                $row->getRelation('cate')->visible(['name']);
                $row->visible(['id', 'name', 'account_cate_id', 'default_price', 'unit', 'sort', 'status', 'create_time', 'update_time']);

            }

            $result = ["code" => 0, "count" => $list->total(), "data" => $list->items()];

            return json($result);
        }
        $cate = (new SpecialCateModel())->column('name','id');
        $this->assign('cate',json_encode($cate));
        return $this->fetch();
    }


    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post('row');

            $province = $this->request->post('province');
            $price = $this->request->post('price');

            try {
                Db::startTrans();
                $this->modelClass->allowField(true)->save($params);
                //添加省份记录
                if ($province) {
                    $data = [];
                    foreach ($province as $key => $item) {
                        if (!$price[$key]) {
                            throw new Exception('信息不能为空');
                        }
                        $data[] = [
                            'special_id' => $this->modelClass->id,
                            'area_name' => $item,
                            'price' => $price[$key],
                            'create_time' => time()
                        ];
                    }
                    (new AreaPrice())->insertAll($data);
                }
                Db::commit();
                $this->isDelRedis();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success("修改成功！");
        }
        return $this->fetch();
    }


    public function edit()
    {
        $id = $this->request->param('id/d', 0);
        $row = $this->modelClass->get($id);
        if ($this->request->isPost()) {
            $params = $this->request->post('row');
            $province = $this->request->post('province');
            $price = $this->request->post('price');

            try {
                Db::startTrans();
                $row->allowField(true)->save($params);

                //删除之前添加的
                (new AreaPrice())->where(['special_id' => $row['id']])->delete();
                if ($province) {
                    $data = [];
                    foreach ($province as $key => $item) {
                        if (!$price[$key]) {
                            throw new Exception('信息不能为空');
                        }
                        $data[] = [
                            'special_id' => $row['id'],
                            'area_name' => $item,
                            'price' => $price[$key],
                            'create_time' => time()
                        ];
                    }
                    (new AreaPrice())->insertAll($data);
                }

                Db::commit();
                $this->isDelRedis();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success("修改成功！");
        }
        $area = (new AreaPrice())->where(['special_id' => $row['id']])->select()->toArray();
        $this->assign('data', $row);
        $this->assign('area', $area);
        return $this->fetch();
    }


}
